using server.Services;
using server.Models;

namespace server.Extensions;

public class Seed
{
    public LibraryContext DB { get; set; }
    public Seed(LibraryContext db)
    {
        DB = db;
    }
    public async Task SeedBooks(string csv_path)
    {
        // var db=new LibraryContext();
        DB.Database.EnsureCreated();
        DB.Books.Clear();
        // DB.Database.EnsureDeleted();
        var options = new BookImportOptions
        {
            Headless = false,
            IdColumn = 0,
            NameColumn = 1,
            PublisherColumn = 2,
            AuthorColumn = 4,
            IndexColumn = 13,
            CountColumn = 14,
            AvailableColumn = 15
        };
        await DB.ImportBooksFromCSV(csv_path, options, 593);
    }

    public async Task SeedRole()
    {
        DB.Database.EnsureCreated();
        DB.Roles.Clear();
        var props = typeof(BasicRole).GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
        var roles = props.Select(prop => prop.GetValue(null) as Role).ToArray();
        if (roles is null || roles.Length == 0)
        {
            throw new Exception("Read basic roles failed!");
        }
        await DB.Roles.AddRangeAsync(roles!);
        await DB.SaveChangesAsync();
    }

    public async Task SeedSuper(string password)
    {
        var super = new User
        {
            Name = "super",
            NickName = "super",
            Role = DB.Roles.Where(r=>r.Name==BasicRole.SuperManager.Name).First(),
            Password = password
            // Password = new MD5Encrypt().Encrypt(password)
        };
        DB.Database.EnsureCreated();
        DB.Users.Add(super);
        await DB.SaveChangesAsync();
    }
}